package controller

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/smartwalle/alipay/v3"
	"go.uber.org/zap"
	"net/http"
	"order_bff/appconfig"
	"order_bff/order"
	"order_bff/pkg"
	"strconv"
)

// 生成支付宝支付链接
func CreateAliPay(c *gin.Context) {
	orderSn := c.PostForm("order_sn")
	if orderSn == "" {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "订单号不能为空",
			"data": nil,
		})
		return
	}
	var privateKey = appconfig.AppConf.AliPayConfig.PrivateKey // 必须，上一步中使用 RSA签名验签工具 生成的私钥
	client, err := alipay.New(appconfig.AppConf.AliPayConfig.AppId, privateKey, false)
	if err != nil {
		zap.S().Info("支付宝实例化失败")
		return
	}
	comment := pkg.Comment()
	detail, err := comment.OrderDetail(context.Background(), &order.OrderDetailRequest{OrderSn: orderSn})
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "订单详情获取失败",
			"data": nil,
		})
		return
	}
	total := strconv.FormatFloat(float64(detail.Price), 'f', 2, 64)
	var p = alipay.TradeWapPay{}
	p.NotifyURL = "http://76cfa435.r7.cpolar.top/notify"
	p.ReturnURL = "http://127.0.0.1:8888/return"
	p.Subject = "滴滴出行"
	p.OutTradeNo = detail.OrderSn
	p.TotalAmount = total
	p.ProductCode = "QUICK_WAP_WAY"

	url, err := client.TradeWapPay(p)
	if err != nil {
		zap.S().Panic(err)
	}

	// 这个 payURL 即是用于打开支付宝支付页面的 URL，可将输出的内容复制，到浏览器中访问该 URL 即可打开支付页面。
	var payURL = url.String()
	fmt.Println(payURL)
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": payURL,
	})
}

func Return(c *gin.Context) {
	orderSn := c.Query("out_trade_no")
	if orderSn == "" {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "订单号不能为空",
			"data": nil,
		})
		return
	}
	comment := pkg.Comment()
	detail, err := comment.OrderDetail(context.Background(), &order.OrderDetailRequest{OrderSn: orderSn})
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "订单详情获取失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": detail,
	})
}

func Notify(c *gin.Context) {
	orderStatus := c.PostForm("trade_status")
	tradeNo := c.PostForm("trade_no")
	outTradeNo := c.PostForm("out_trade_no")
	comment := pkg.Comment()
	if orderStatus == "TRADE_SUCCESS" {
		_, err := comment.UpdateOrder(context.Background(), &order.UpdateOrderRequest{
			OrderSn: outTradeNo,
			TradeNo: tradeNo,
			Status:  orderStatus,
			PayType: 1,
		})
		if err != nil {
			zap.S().Info("修改订单信息失败")
		}
	} else {
		zap.S().Info("订单支付成功")
	}
}
